<template>
  <div>
    <el-card shadow="never" class="mb20">
      <div class="filter-container" style="text-align: right;">
        <el-button class="filter-item" type="primary" icon="el-icon-plus" title="新建扩展字段" @click="handleAdd"></el-button>
        <el-button v-if="tableId" class="filter-item" type="primary" icon="el-icon-attract" title="同步新字段" @click="handleSync"></el-button>
      </div>
    </el-card>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        stripe
        fit
        highlight-current-row>
        <el-table-column prop="columnName" label="列名" align="center"></el-table-column>
        <el-table-column prop="columnComment" label="字段描述" width="200" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.editable">
              <el-input placeholder="请输入" v-model="scope.row.columnComment" @blur="handleUpdateComment(scope.row)"/>
            </div>
            <div v-else>
              <span>{{scope.row.columnComment}}</span>
              <span v-if="scope.row.columnId">&nbsp;&nbsp;<i class="el-icon-edit-outline" title="点击修改" style="cursor: pointer;" @click="scope.row.editable = true"></i></span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="数据类型" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row | dataTypeFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="列类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.columnType === 'EXT_COLUMN'">扩展列</span>
            <span v-else>基础表列</span>
          </template>
        </el-table-column>
        <el-table-column label="是否允许空" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.isNullable === 'YES'">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column label="主键" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.primaryKey">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column label="外键" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.foreignKey">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column prop="primaryTableColumn" label="对应主表的列" align="center"></el-table-column>
        <el-table-column align="center" prop="valueType" label="字段值类型">
        </el-table-column>
        <el-table-column label="操作" min-width="100" align="center">
          <template slot-scope="scope">
            <div v-show="scope.row.columnType === 'EXT_COLUMN'">
              <el-button type="primary" size="mini" circle icon="el-icon-edit" @click="handleEdit(scope.row, scope.$index)"></el-button>
              <el-button type="danger" size="mini" circle icon="el-icon-delete" @click="handleRemove(scope.row, scope.$index)"></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px;text-align: center;">
        <el-button v-if="cancelText" @click="handleCancel">{{cancelText}}</el-button>
        <el-button v-if="submitText" type="primary" @click="handleSubmit">{{submitText}}</el-button>
      </div>

      <el-dialog :visible.sync="dialogVisible" width="800px" :title="title">
        <div style="height: 520px; overflow: auto;">
          <PropCreate cancelText="取消" @onCancel="handleDialogCancel" submitText="提交" :tableId="tableId" :tableName="tableName" :row="row" @onSubmit="handleDialogSubmit"></PropCreate>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { getListByTableId, remove, updateComment, synchronize } from '@/api/workflow/form/columns'
import PropCreate from './PropCreate'
import enums from '@/views/workflow/utils/enum'
export default {
  components: {
    PropCreate
  },
  props: {
    tableId: {
      type: String,
      default: ''
    },
    tableName: {
      type: String,
      default: ''
    },
    columns: { // 表的基础列
      type: Array,
      default: function() {
        return []
      }
    },
    cancelText: { // 取消
      type: String,
      default: ''
    },
    submitText: { // 提交
      type: String,
      default: ''
    }
  },
  filters: {
    dataTypeFilter(row) {
      let typeText = row.dataType
      if (Object.keys(enums.DATA_TYPE)[0] === row.dataType) {
        typeText += `(${row.characterMaximumLength})`
      } else if (Object.keys(enums.DATA_TYPE)[1] === row.dataType) {
        typeText += `(${row.numericScale}, ${row.numericPrecision})`
      } if (Object.keys(enums.DATA_TYPE)[2] === row.dataType) {
        typeText += `(${row.datetimePrecision})`
      }
      return typeText
    }
  },
  data() {
    return {
      title: '新增扩展字段',
      dialogVisible: false,
      list: null,
      listLoading: false,
      extColumns: [], // 扩展列
      row: {} // 修改的行
    }
  },
  watch: {
    tableId(val) {
      this.fetchData()
    },
    tableName(val) {
      console.log(val)
    },
    columns: {
      deep: true,
      handler(val) {
        this.list = this.extColumns.concat(val)
      }
    },
    extColumns: {
      deep: true,
      handler(val) {
        this.list = val.concat(this.columns)
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      if (!this.tableId) return
      this.listLoading = true
      getListByTableId(this.tableId).then(response => {
        response.data.forEach(element => {
          element.editable = false
        })
        this.list = response.data
        this.listLoading = false
      })
    },
    handleAdd() { // 新建扩展字段
      this.title = '新增扩展字段'
      this.dialogVisible = true
    },
    handleDialogCancel() {
      this.dialogVisible = false
    },
    handleEdit(row, index) { // 修改扩展字段
      row.rowIndex = index
      this.row = row
      this.title = '修改扩展字段'
      this.dialogVisible = true
    },
    handleDialogSubmit(data) {
      this.dialogVisible = false
      if (this.tableId) {
        this.fetchData()
      } else {
        if (data.rowIndex >= 0) {
          this.list.find((element, index) => {
            if (index === data.rowIndex) {
              delete data.rowIndex
              element = data
              return true
            }
          })
        } else {
          delete data.rowIndex
          this.extColumns.unshift(data)
        }
      }
    },
    handleRemove(row, index) { // 删除扩展字段
      this.$confirm('确定要删除该扩展字段吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        if (this.tableId) { // 如果是修改自定义表单，则直接操作数据库
          remove(row.columnId).then(res => {
            this.$message.success('删除成功')
            this.fetchData()
          })
        } else { // 如果是新增自定义表单，则执行前端操作
          this.extColumns.splice(index, 1)
        }
      })
    },
    handleUpdateComment(row) { // 单独修改字段描述
      if (!row.columnId) return // 新增的时候columnId没值
       const post = {
        columnId: row.columnId,
        columnComment: row.columnComment
      }
      updateComment(post).then(res => {
        this.$message.success('修改成功')
        row.editable = false
      })
    },
    handleSync() { // 同步新字段，表单对应的数据库原始表格添加字段时，通过此操作把新字段同步过来
      synchronize(this.tableId).then(res => {
        this.$message.success('同步成功')
        this.fetchData()
      }) 
    },
    handleCancel() {
      this.$emit('onCancel')
    },
    handleSubmit() {
      this.$emit('onSubmit', this.list)
    }
  }
}
</script>
